package org.jeecg.modules.demo.ddyht.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.ddyht.controller.DdygPiciController;
import org.jeecg.modules.demo.ddyht.controller.YueController;
import org.jeecg.modules.demo.ddyht.entity.DdygInventory;
import org.jeecg.modules.demo.ddyht.entity.DdygPici;
import org.jeecg.modules.demo.ddyht.entity.JxcHbzj;
import org.jeecg.modules.demo.ddyht.mapper.DdygPiciMapper;
import org.jeecg.modules.demo.ddyht.service.IDdygInventoryService;
import org.jeecg.modules.demo.ddyht.service.IDdygPiciService;
import org.jeecg.modules.demo.ddyht.service.IJxcHbzjService;
import org.jeecg.modules.demo.jxcx.Utils.R;
import org.jeecg.modules.demo.jxcx.Utils.RandomUtil;
import org.jeecg.modules.demo.jxcx.po.*;
import org.jeecg.modules.demo.jxcx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 批次信息
 * @Author: jeecg-boot
 * @Date:   2025-02-23
 * @Version: V1.0
 */
@Service
@Slf4j
public class DdygPiciServiceImpl extends ServiceImpl<DdygPiciMapper, DdygPici> implements IDdygPiciService {

    @Autowired
    private IDdygInventoryService ddygInventoryService;
    @Autowired
    private JxcPiciService jxcPiciService;
    @Autowired
    private JxcSaleService jxcSaleService;
    @Autowired
    private JxcStockService jxcStockService;
    @Autowired
    private JxcSupplierService jxcSupplierService;
    @Autowired
    private JxcCustomService jxcCustomService;
    @Autowired
    private JxcCzrzService jxcCzrzService;
    @Autowired
    private IJxcHbzjService jxcHbzjService;
    @Autowired
    private YueController yueController;
    @Override
    public List<DdygPici> getBycompany(String username) {
        return baseMapper.getBycompany(username);
    }

    @Override
    public Result<String> add(List<DdygPici> ddygPici) {
        log.info("数据新增开始" + ddygPici.toString());
        BigDecimal allamount1 = new BigDecimal("0.00");
        BigDecimal allamount2 = new BigDecimal("0.00");
        if (StringUtils.isNotBlank(ddygPici.get(0).getDiscount())){
            allamount2 = new BigDecimal(ddygPici.get(0).getDiscount());
        }
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDateTime = now.format(formatter);
        String only1 = RandomUtil.generateRandomString();
        String id = now.format(formatter2) + only1;
        String CompanyId = ddygPici.get(0).getCompanyId();
        String Traner = ddygPici.get(0).getTraner().trim();
//        String IsPay = ddygPici.get(0).getIsPay();
        String IsPay = "";
        if(StringUtils.isNotBlank(ddygPici.get(0).getIsPay())){
            IsPay = ddygPici.get(0).getIsPay();
        }else {
            IsPay = "否";
        }
        String PaymentMethod = "无";
        if (IsPay.equals("是")){
            PaymentMethod = ddygPici.get(0).getPaymentMethod();
        }
        String orstate = ddygPici.get(0).getOrstate();
        List<String> modellist = new ArrayList<>();
        for (int i = 0; i < ddygPici.size(); i++) {
            modellist.add(ddygPici.get(i).getModel());
        }
        for (int i = 0; i < ddygPici.size(); i++) {
            String only = RandomUtil.generateRandomString();
            String model = ddygPici.get(i).getModel().trim();
            String number = ddygPici.get(i).getNumber().trim();
            String unitPrice = ddygPici.get(i).getUnitPrice().trim();
            //用bigdecimal计算总额，小数点位数为0
            String totalfee = String.valueOf(new BigDecimal(number).multiply(new BigDecimal(unitPrice)));
            allamount1 = allamount1.add(new BigDecimal(totalfee));
            ddygPici.get(i).setAmount(totalfee);
            ddygPici.get(i).setId(id);
            ddygPici.get(i).setPaymentMethod(PaymentMethod);
            if (StringUtils.isNotBlank(ddygPici.get(i).getIsPay())){
                ddygPici.get(i).setIsPay(ddygPici.get(i).getIsPay());
            }else {
                ddygPici.get(i).setIsPay(IsPay);
            }
            if (StringUtils.isNotBlank(ddygPici.get(i).getRemark())){
                ddygPici.get(i).setRemark(ddygPici.get(i).getRemark());
            }else {
                ddygPici.get(i).setRemark(null);
            }
            //生成8位随机整数

            if (orstate.equals("1")) {
                ddygPici.get(i).setRealnumber(number);
            }
            ddygPici.get(i).setOnlyid(only + id);
            save(ddygPici.get(i));
            if (ddygInventoryService.getBymodelcompany(model, CompanyId) != null){
                if (orstate.equals("1")) {
                    DdygInventory ddygInventory = ddygInventoryService.getBymodelcompany(model, CompanyId);
                    ddygInventory.setNumber(String.valueOf(new BigDecimal(ddygInventory.getNumber()).add(new BigDecimal(number))));
                    BigDecimal multiply = new BigDecimal(unitPrice).multiply(new BigDecimal(number));
                    ddygInventory.setAmount(String.valueOf(new BigDecimal(ddygInventory.getAmount()).add(multiply)));
                    ddygInventory.setCreateTime(formattedDateTime);
                    ddygInventoryService.updateById(ddygInventory);
                }
//                else {
//                    DdygInventory ddygInventory = ddygInventoryService.getBymodelcompany(model, CompanyId);
//                    ddygInventory.setNumber(String.valueOf(new BigDecimal(ddygInventory.getNumber()).subtract(new BigDecimal(number))));
//                    ddygInventory.setCreateTime(formattedDateTime);
////					BigDecimal multiply = new BigDecimal(unitPrice).multiply(new BigDecimal(number));
////					ddygInventory.setAmount(String.valueOf(new BigDecimal(ddygInventory.getAmount()).subtract(multiply)));
//                    ddygInventoryService.updateById(ddygInventory);
//                }
            }else {
                DdygInventory ddygInventory = new DdygInventory();
                if (orstate.equals("1")) {
                    ddygInventory.setAmount(String.valueOf(new BigDecimal(ddygPici.get(i).getAmount())));
                    ddygInventory.setNumber(String.valueOf(new BigDecimal(ddygPici.get(i).getNumber())));
                    ddygInventory.setModel(ddygPici.get(i).getModel());
                    ddygInventory.setCompanyId(CompanyId);
                    ddygInventory.setCreateTime(formattedDateTime);
                    ddygInventoryService.save(ddygInventory);
                }
//                else {
////					ddygInventory.setAmount("-" + new BigDecimal(ddygPici.get(i).getAmount()));
////                    ddygInventory.setNumber("-" + new BigDecimal(ddygPici.get(i).getNumber()));
//                    ddygInventory.setNumber("0");
//                    ddygInventory.setModel(ddygPici.get(i).getModel());
//                    ddygInventory.setCompanyId(CompanyId);
//                    ddygInventory.setCreateTime(formattedDateTime);
//                    ddygInventoryService.save(ddygInventory);
//                }
            }


            JxcCzrz jxcCzrz = new JxcCzrz();
            jxcCzrz.setId(DdygPiciController.setczrzid(id));
            jxcCzrz.setCompanyId(CompanyId);
            jxcCzrz.setInfor("型号:" + ddygPici.get(i).getModel() + "数量:" + ddygPici.get(i).getNumber() + "单价:" + ddygPici.get(i).getUnitPrice() + "金额:" + totalfee + "交易方:" + Traner);
            if (orstate.equals("1")) {
                jxcCzrz.setType("进货批次新增");
                jxcCzrz.setOrstate("进货");
            } else {
                jxcCzrz.setType("销货批次新增");
                jxcCzrz.setOrstate("销货");
            }

            R add = jxcCzrzService.add(jxcCzrz);
        }
        if (orstate.equals("1")) {
            //进货
            JxcStock jxcStock = new JxcStock();
            if (StringUtils.isNotBlank(ddygPici.get(0).getDiscount())){
                jxcStock.setAmount(String.valueOf(allamount2));
            }else {
                jxcStock.setAmount(String.valueOf(allamount1));
            }
            jxcStock.setCompanyId(CompanyId);
            jxcStock.setCreateTime(formattedDateTime);
            jxcStock.setId(id);
            jxcStock.setPaymentMethod(PaymentMethod);
            jxcStock.setSeller(Traner);
            jxcStock.setIsPay(IsPay);
            jxcStock.setModel(modellist.toString());
//            if (Traner.equals("期初库存")){
//
//            }else {
                if (StringUtils.isNotBlank(ddygPici.get(0).getDiscount()) && IsPay.equals("是")){
                    if (jxcHbzjService.selectbyPaymentMethod(PaymentMethod,CompanyId) != null){
                        JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(PaymentMethod, CompanyId);
                        jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).subtract(allamount2)));
                        jxcHbzj.setCreateTime(formattedDateTime);
                        jxcHbzjService.updateById(jxcHbzj);
                    }else {
                        JxcHbzj jxcHbzj2 = new JxcHbzj();
                        jxcHbzj2.setAmount("-" + allamount2);
                        jxcHbzj2.setCompanyId(CompanyId);
                        jxcHbzj2.setCreateTime(formattedDateTime);
                        jxcHbzj2.setId(id);
                        jxcHbzj2.setOther("支出");
                        jxcHbzj2.setPaymethod(PaymentMethod);
                        jxcHbzjService.save(jxcHbzj2);

                    }
                    JxcCzrz jxcCzrz = new JxcCzrz();
                    jxcCzrz.setId(DdygPiciController.setczrzid(id));
//                jxcCzrz.setCreatTime(formattedDateTime);
                    jxcCzrz.setCompanyId(CompanyId);
                    jxcCzrz.setOtherid("货币资金");
                    jxcCzrz.setOrstate("进货支出-"+Traner);
                    jxcCzrz.setType(PaymentMethod);
                    jxcCzrz.setInfor("-" + allamount2);
                    jxcCzrz.setCreatTime(formattedDateTime);
                    yueController.setHbzj(jxcCzrz,PaymentMethod,allamount2.toString(),"-");
                    jxcCzrzService.add(jxcCzrz);
                }else {

                    if (Traner.equals("期初库存")){

                    }else {
                        this.Stockadd(jxcStock, formattedDateTime, id);
                    }
                }
//            }
            JxcCzrz jxcCzrz1 = new JxcCzrz();
            jxcCzrz1.setId(DdygPiciController.setczrzid(id));
            jxcCzrz1.setCompanyId(CompanyId);
            if (StringUtils.isNotBlank(ddygPici.get(0).getDiscount())){
                jxcCzrz1.setInfor("交易方:" + Traner + "金额:" + String.valueOf(allamount2));
            }else {
                jxcCzrz1.setInfor("交易方:" + Traner + "金额:" + String.valueOf(allamount1));
            }
            jxcCzrz1.setType("进货单新增");
            R add = jxcCzrzService.add(jxcCzrz1);
            log.info("数据新增结束-进货" + jxcStock.toString());
            jxcStockService.save(jxcStock);
            setamount(CompanyId);
            return Result.OK("添加成功！");
        } else {
            //销售
            JxcSale jxcSale = new JxcSale();
            if (StringUtils.isNotBlank(ddygPici.get(0).getDiscount())){
                jxcSale.setAmount(String.valueOf(allamount2));
            }else {
                jxcSale.setAmount(String.valueOf(allamount1));
            }
            jxcSale.setBuyer(Traner);
            jxcSale.setCompanyId(CompanyId);
            jxcSale.setCreateTime(formattedDateTime);
            jxcSale.setId(id);
            jxcSale.setIsPay(IsPay);
            jxcSale.setPaymentMethod(PaymentMethod);
            jxcSale.setModel(modellist.toString());
            if (StringUtils.isNotBlank(ddygPici.get(0).getDiscount()) && IsPay.equals("是")){
                if (jxcHbzjService.selectbyPaymentMethod(PaymentMethod,CompanyId) != null){
                    JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(PaymentMethod, CompanyId);
                    jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).add(allamount2)));
                    jxcHbzj.setCreateTime(formattedDateTime);
                    jxcHbzjService.updateById(jxcHbzj);
                }else {
                    JxcHbzj jxcHbzj2 = new JxcHbzj();
                    jxcHbzj2.setAmount(String.valueOf(allamount2));
                    jxcHbzj2.setCompanyId(CompanyId);
                    jxcHbzj2.setCreateTime(formattedDateTime);
                    jxcHbzj2.setId(id);
                    jxcHbzj2.setOther("收入");
                    jxcHbzj2.setPaymethod(PaymentMethod);
                    jxcHbzjService.save(jxcHbzj2);

                }
                JxcCzrz jxcCzrz = new JxcCzrz();
                jxcCzrz.setId(DdygPiciController.setczrzid(id));
                jxcCzrz.setCompanyId(CompanyId);
                jxcCzrz.setOtherid("货币资金");
                jxcCzrz.setOrstate("销货收入-"+Traner);
                jxcCzrz.setType(PaymentMethod);
                jxcCzrz.setInfor("+" + allamount2);
                jxcCzrz.setCreatTime(formattedDateTime);
                yueController.setHbzj(jxcCzrz,PaymentMethod,allamount2.toString(),"+");
                jxcCzrzService.add(jxcCzrz);
            }else {
                this.Saleadd(jxcSale, formattedDateTime, id);
            }
            JxcCzrz jxcCzrz1 = new JxcCzrz();
            jxcCzrz1.setId(DdygPiciController.setczrzid(id));
            jxcCzrz1.setCompanyId(CompanyId);
            if (StringUtils.isNotBlank(ddygPici.get(0).getDiscount())){
                jxcCzrz1.setInfor("交易方:" + Traner + "金额:" + String.valueOf(allamount2));
            }else {
                jxcCzrz1.setInfor("交易方:" + Traner + "金额:" + String.valueOf(allamount1));
            }
            jxcCzrz1.setType("销货单新增");
            R add = jxcCzrzService.add(jxcCzrz1);
            log.info("数据新增结束-销货" + jxcSale.toString());
            jxcSaleService.save(jxcSale);
            setamount(CompanyId);
            return Result.OK("添加成功！");
//		ddygPiciService.save(ddygPici);
        }
    }

    @Override
    public List<DdygPici> getBycompanySale(String username, String number) {
        return baseMapper.getBycompanySale(username,number);
    }

    @Override
    public List<DdygPici> getBycompanyStock(String username, String number) {
        return baseMapper.getBycompanyStock(username,number);
    }

    @Override
    public List<DdygPici> getByall(String companyId, String number, String model) {
        return baseMapper.getByall(companyId,number,model);
    }

    @Override
    public List<DdygPici> getByalltwo(String companyId, String model, String orstate) {
        return baseMapper.getByalltwo(companyId,model,orstate);
    }

    @Override
    public List<DdygPici> getByallId(String username, String id) {
        return baseMapper.getByallId(username,id);
    }

    @Override
    public void deleteByall(String companyId, String id, String orstate) {
        baseMapper.deleteByall(companyId,id,orstate);
    }

    @Override
    public List<DdygPici> getByModel(String companyId, String model, String orstate) {
        return baseMapper.getByModel(companyId,model,orstate);
    }

    @Override
    public DdygPici getByModelId(String onlyid, String companyId, String model, String number) {
        return baseMapper.getByModelId(onlyid,companyId,model,number);
    }

    private String czrzid = "1231242131231231";
    @Override
    public String setczrzid(String id) {
        String s = RandomUtil.generateRandomString1(id, id.length());
        if (czrzid.equals(id)){
            czrzid = id+s.substring(0,5);
            return id+s.substring(0,5);
        }
        czrzid = s;
        return s;
    }

    @Override
    public DdygPici getByOnlyId(String onlyid, String companyId) {
        return baseMapper.getByOnlyId(onlyid,companyId);
    }

    public void Stockadd(JxcStock jxcStock,String formattedDateTime,String id){
        jxcStock.setId(id);
        jxcStock.setCreateTime(formattedDateTime);
        String seller = jxcStock.getSeller();
        String companyId = jxcStock.getCompanyId();
        String isPay = jxcStock.getIsPay();
//        String number = jxcStock.getNumber();
//        String unitPrice = jxcStock.getUnitPrice();
        //用bigdecimal计算总额，小数点位数为0
        String totalfee = String.valueOf(new BigDecimal(jxcStock.getAmount()));
        JxcSupplier jxcSupplier = jxcSupplierService.getBy(seller, companyId);
        if (jxcSupplier == null){
            JxcSupplier jxcSupplier1 = new JxcSupplier();
            jxcSupplier1.setId(id);
            jxcSupplier1.setCreateTime(formattedDateTime);
            jxcSupplier1.setName(seller);
            jxcSupplier1.setCompanyId(companyId);
            jxcSupplier1.setAmount(totalfee);
            jxcSupplier1.setIsPay(isPay);
            jxcSupplierService.save(jxcSupplier1);

            JxcCzrz jxcCzrz1 = new JxcCzrz();
            jxcCzrz1.setId(DdygPiciController.setczrzid(id));
            jxcCzrz1.setCompanyId(companyId);
//            jxcCzrz1.setInfor("姓名:"+seller+"金额:"+totalfee);
//            jxcCzrz1.setType("供应商新增");
            jxcCzrz1.setOtherid("应收应付-批次新增");
            jxcCzrz1.setOrstate("应付款-"+seller);
            jxcCzrz1.setType("应付款-"+seller);
            jxcCzrz1.setInfor("" + totalfee);
            jxcCzrz1.setCreatTime(formattedDateTime);
            yueController.setSupplier(jxcCzrz1,seller,totalfee,"");
            jxcCzrzService.add(jxcCzrz1);
        }else {
            BigDecimal add1 = new BigDecimal(jxcSupplier.getAmount()).add(new BigDecimal(totalfee));
            jxcSupplier.setAmount(add1.toString());
            jxcSupplier.setCreateTime(formattedDateTime);
            jxcSupplierService.updateById(jxcSupplier);

            JxcCzrz jxcCzrz1 = new JxcCzrz();
            jxcCzrz1.setId(DdygPiciController.setczrzid(id));
            jxcCzrz1.setCompanyId(companyId);
//            jxcCzrz1.setInfor("姓名:"+seller+"金额+"+totalfee);
//            jxcCzrz1.setType("供应商修改");
            jxcCzrz1.setOtherid("应收应付-批次新增");
            jxcCzrz1.setOrstate("应付款-"+seller);
            jxcCzrz1.setType("应付款-"+seller);
            jxcCzrz1.setInfor("" + totalfee);
            jxcCzrz1.setCreatTime(formattedDateTime);
            yueController.setSupplier(jxcCzrz1,seller,totalfee,"");
            jxcCzrzService.add(jxcCzrz1);
        }
        jxcStock.setAmount(totalfee);
    }
    public void Saleadd(JxcSale jxcSale,String formattedDateTime,String id){
        jxcSale.setId(id);
        jxcSale.setCreateTime(formattedDateTime);
        String isPay = jxcSale.getIsPay();
        String buyer = jxcSale.getBuyer();
        String companyId = jxcSale.getCompanyId();
//        String number = jxcSale.getNumber();
//        String unitPrice = jxcSale.getUnitPrice();
        //用bigdecimal计算总额，小数点位数为0
        String totalfee = String.valueOf(new BigDecimal(jxcSale.getAmount()));
        JxcCustom jxcCustom = jxcCustomService.getBy(buyer, companyId);
        if (jxcCustom == null){
            JxcCustom jxcCustom1 = new JxcCustom();
            jxcCustom1.setId(id);
            jxcCustom1.setCreateTime(formattedDateTime);
            jxcCustom1.setName(buyer);
            jxcCustom1.setCompanyId(companyId);
            jxcCustom1.setAmount(totalfee);
            jxcCustom1.setIsPay(isPay);
            jxcCustomService.save(jxcCustom1);

            JxcCzrz jxcCzrz1 = new JxcCzrz();
            jxcCzrz1.setId(DdygPiciController.setczrzid(id));
            jxcCzrz1.setCompanyId(companyId);
//            jxcCzrz1.setInfor("姓名:"+buyer+"金额:"+totalfee);
//            jxcCzrz1.setType("供应商新增");
            jxcCzrz1.setOtherid("应收应付-批次新增");
            jxcCzrz1.setOrstate("应收款-"+buyer);
            jxcCzrz1.setType("应收款-"+buyer);
            jxcCzrz1.setInfor("" + totalfee);
            jxcCzrz1.setCreatTime(formattedDateTime);
            yueController.setCustom(jxcCzrz1,buyer,totalfee,"");
            jxcCzrzService.add(jxcCzrz1);
        }else {
            BigDecimal add1 = new BigDecimal(jxcCustom.getAmount()).add(new BigDecimal(totalfee));
            jxcCustom.setAmount(add1.toString());
            jxcCustom.setCreateTime(formattedDateTime);
            jxcCustomService.updateById(jxcCustom);

            JxcCzrz jxcCzrz1 = new JxcCzrz();
            jxcCzrz1.setId(DdygPiciController.setczrzid(id));
            jxcCzrz1.setCompanyId(companyId);
//            jxcCzrz1.setInfor("姓名:"+buyer+"金额+"+totalfee);
//            jxcCzrz1.setType("客户修改");
            jxcCzrz1.setOtherid("应收应付-批次新增");
            jxcCzrz1.setOrstate("应收款-"+buyer);
            jxcCzrz1.setType("应收款-"+buyer);
            jxcCzrz1.setInfor("" + totalfee);
            jxcCzrz1.setCreatTime(formattedDateTime);
            yueController.setCustom(jxcCzrz1,buyer,totalfee,"");
            jxcCzrzService.add(jxcCzrz1);
        }
        jxcSale.setAmount(totalfee);
    }
    public void setamount(String companyId){
        List<DdygInventory> bycompany = ddygInventoryService.getBycompany(companyId);
        for (int i = 0; i < bycompany.size(); i++) {
            DdygInventory ddygInventory = bycompany.get(i);
            String model = ddygInventory.getModel();
            List<DdygPici> byall = getByall(companyId, "1", model);
            if (byall.size() > 0){
                BigDecimal allamount = new BigDecimal(0);
                BigDecimal allNumber = new BigDecimal(0);
                for (int j = 0; j < byall.size(); j++) {
                    DdygPici ddygPici = byall.get(j);
                    allamount = allamount.add(new BigDecimal(ddygPici.getAmount()));
                    allNumber = allNumber.add(new BigDecimal(ddygPici.getNumber()));
                }
                if (allNumber != BigDecimal.ZERO){
                    BigDecimal avgunitPrice = allamount.divide(allNumber, 2, BigDecimal.ROUND_HALF_UP);
                    ddygInventory.setUnitPrice(avgunitPrice.toString());
                    ddygInventory.setAmount(avgunitPrice.multiply(new BigDecimal(ddygInventory.getNumber())).toString());
                }else {
                    ddygInventory.setUnitPrice("0");
                    ddygInventory.setAmount("0");
                }
//                BigDecimal avgunitPrice = allamount.divide(allNumber, 2, BigDecimal.ROUND_HALF_UP);
//                ddygInventory.setAmount(avgunitPrice.multiply(new BigDecimal(ddygInventory.getNumber())).toString());
                ddygInventoryService.updateById(ddygInventory);

            }else {
                DdygInventory bymodelcompany = ddygInventoryService.getBymodelcompany(model, companyId);
                bymodelcompany.setAmount("0");
                ddygInventoryService.updateById(bymodelcompany);
            }
        }
    }
}
